package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.ShopOrderBean;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.https.OtherHttp;
import com.ruike.alisurface.serialport.ShopInfoUtils;
import com.ruike.alisurface.serialport.SlotShopInfoBean;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_mqtt.MqttService;
import com.voodoo.lib_utils.SharedUtils;
import com.voodoo.serialport.util.ByteUtils;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.IC2_SLOT_NUM;

/**
 * 商品出货页
 */
public class PayShopShipment_Aty extends BaseAty implements ApiListener {
    @BindView(R.id.selectPay_countDown_tv)
    TextView selectPayCountDownTv;
    List<String> serialList = new ArrayList<>();//货道串口返回值集合
    int shopcount = 0;//出货数量
    boolean isSuccess = true;//是否出货成功
    List<SlotShopInfoBean> slotBeanList = new ArrayList<>();//未出货货道指令集合
    private boolean isYiBaoPay;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_payshop_shipment;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        startCountdownTimer(180, selectPayCountDownTv, PayShipmentResult_Aty.class);
    }

    ShopOrderBean shopOrderBean;
    List<ShopOrderBean.DataBean.DetailsBean> slotList = new ArrayList<>();

    @Override
    protected void initData() {
        Constant.isShopShipment = true;
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String json = getIntent().getStringExtra("shopOrderBean");
            isYiBaoPay = json.contains("YiBaoPay");
            shopOrderBean = GsonUtils.fromJson(json, ShopOrderBean.class);
            slotList.addAll(shopOrderBean.getData().getDetails());
            shopcount = slotList.size();
            L.iTag("toshop", " 出货数量 ======" + shopcount);
            doShopShipment();
        }

        ShopInfoUtils.getInstance().setSlotCallBacK(new ShopInfoUtils.SlotCallBacK() {
            @Override
            public void onSlotSuccess(String serilamsg, byte[] resultBytes) {
                serialList.add(serilamsg);
                ShopInfoUtils.getInstance().Timercancal();
                L.i("toshop", "信息的比较  =slotcount=slotList.size()= ", slotcount, slotList.size());
                if (slotcount < slotList.size()) {
                    doShopShipment();
                } else {
                    L.i("toshop", "onSlotSuccess 整个商品出货完成 ");
                }
                --shopcount;
                L.i("toshop", " 出货数量递减======" + shopcount);
                todoPageAty();
            }

            @Override
            public void onSlotFail(int slotindex) {
                if (slotcount < slotList.size()) {
                    doShopShipment();
                } else {
                    L.i("toshop", "onSlotFail  整个商品出货完成 ");
                }
                --shopcount;
                L.i("toshop", " 出货数量递减======" + shopcount);
                todoPageAty();
            }
        });
    }

    int slotcount = 0;
    Handler mHandler = new Handler();

    public void doShopShipment() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (slotList.size() > 0) {
                    ShopInfoUtils.getInstance().TodoShipmentSlot(slotList.get(slotcount).getSlotIndex(), slotList.get(slotcount).getSlotTypeId(), slotList.get(slotcount).getQuantity());
                    slotcount++;
                }
            }
        });
    }


    /**
     * 解析指令及上传完结信息
     */
    public void todoPageAty() {
        L.iTag("toshop", " 计时  出货数量--", shopcount, "开始上传信息及跳转完成页");
        if (shopcount == 0) {
            shopcount = -1;
            String datas = "";
            L.iTag("toshop", "开始完成接口2  serialList.size()  " + serialList.size());
            if (serialList.size() > 0) {
                ShopInfoUtils.dllist.clear();
                for (int i = 0; i < serialList.size(); i++) { //外层获取指令
                    String[] data_code = serialList.get(i).split(" ");
                    int slot_num = SharedUtils.getInstance().getInt(IC2_SLOT_NUM, 100);//得到每一个柜子的最大货道
                    int index = ((Integer.parseInt(data_code[0]) - 10) * slot_num) + Integer.parseInt(data_code[5], 16) + 1;
                    byte[] hexArray = ByteUtils.hexToByteArr(serialList.get(i).replace(" ", ""));

                    L.iTag("toshop", "开始完成接口3 index  " + index);
                    for (int s = 0; s < slotList.size(); s++) {//内层获取货道出货类型
                        L.iTag("toshop", "开始完成接口4 index  " + slotList.get(s).getSlotIndex());
                        if (slotList.get(s).getSlotIndex() == index) {
                            ShopInfoUtils.getInstance().analyzeSlot(hexArray, slotList.get(s).getSlotTypeId());
                        }
                    }
                }
                datas = GsonUtils.toJson(serialList);
                if (ShopInfoUtils.dllist.size() > 0) {
                    for (SlotShopInfoBean slotBean : ShopInfoUtils.dllist) {
                        if (slotBean.getZdcount() < slotBean.getCount() || slotBean.getZdcount() == 0) {
                            slotBeanList.add(slotBean);
                            isSuccess = false;
                        }
                    }
                } else {
                    isSuccess = false;
                }
                ShopInfoUtils.getInstance().sendCheckoutnotify(shopOrderBean.getData().getId(), MqttService.mqttClient);
            } else {
                isSuccess = false;
            }
            L.iTag("toshop", "开始完成接口3    " + "延迟100毫秒");
            SystemClock.sleep(100);
            if (isYiBaoPay) {
                OtherHttp.endOrder(shopOrderBean.getData().getId(), isSuccess, datas + "完成", this);
            } else {
                HashMap<String, Object> map = new HashMap<>();
                map.put("OrderNo", shopOrderBean.getData().getId());
                map.put("IsEnd", isSuccess);
                map.put("Remark", datas + "完成");
                L.iTag("toshop", "开始完成接口4");
                MchApiHttp.getOrderIsEnd(this, map);
            }
        }
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (OtherHttp.END_ORDER_URL.contentEquals(requestUrl) || requestUrl.endsWith("OrderIsEnd")) {
            L.iTag("toshop", "OrderIsEnd   onSuccess === +出貨完成");
            todoPage();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        if (OtherHttp.END_ORDER_URL.contentEquals(requestUrl) || requestUrl.endsWith("OrderIsEnd")) {
            L.iTag("toshop", "OrderIsEnd   onSuccess === +出貨完成");
            todoPage();
        }
    }


    private String paytype;//支付类型

    /**
     * 相关信息及跳转下一页
     */
    public void todoPage() {
        Bundle bundle = getIntent().getExtras();
        paytype = bundle.getString("pay_type", "wechat");
        L.iTag("出货  页=", "写入订单号" + shopOrderBean.getData().getId());
        SharedUtils.getInstance().putString(ShareKey.ORDER_RESULT, shopOrderBean.getData().getId());
        bundle.putString("order_id", shopOrderBean.getData().getId());
        bundle.putDouble("order_money", shopOrderBean.getData().getTotal_fee());
        bundle.putDouble("actual_money", shopOrderBean.getData().getPay_fee());

        if (slotBeanList.size() > 0) {
            bundle.putBoolean("isSuccess", isSuccess);
            bundle.putSerializable("slotList", (Serializable) slotBeanList);
        } else {
            bundle.putBoolean("isSuccess", isSuccess);
        }
        startActivity(PayShipmentResult_Aty.class, bundle);
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Constant.isShopShipment = false;
        L.i("onDestroy 出货页销毁 ");
        ShopInfoUtils.getInstance().setSlotCallBacK(null);
        shopOrderBean = null;
        serialList.clear();
        serialList = null;
        slotList.clear();
        slotList = null;
        slotBeanList.clear();
        slotBeanList = null;
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
    }
}
